<template>
  <div>
    <div class="attach-buttons-wrap">
      <!-- 工具按钮  :disabled="
        toolbtnDisabled({ btn,selectedRowKeys}) ? true : false
        "-->
      <a-button
        v-bind="btn.props"
        @click="btn.onclick({ selectedRowKeys })"
        v-for="btn in attachButtons"
        :key="btn.name"
        :style="{
          marginRight: '8px',
          display: toolbtnShow({ btn }) ? 'inline-block' : 'none',
        }"
       
      >
        {{ btn.name }}
      </a-button>
    </div>
    <a-table
      v-bind="{
        loading: localLoading,
        pagination: localPagination,
        rowSelection: localRowSelection,
        rowKey: 'id',
        ...$attrs,
      }"
      :dataSource="dataSource"
      class="tableStyle"
    >
      <!-- 自定义渲染单元格   -->
      <template #bodyCell="{ text, record, index, column }">
        <!-- 操作列 -->
        <template v-if="column.dataIndex === 'operation'">
          <a-button
            v-for="(item, itemIndex) in column.buttons"
            type="link"
            :key="itemIndex"
            @click="item.onclick({ text, record, index, column })"
            :disabled="
              btnDisabled({ item, record}) ? true : false
            "
            :style="{
              marginRight: '8px',
              display: btnShow({ item, record})
                ? 'inline-block'
                : 'none',
              ...(item.style || {}),
            }"
          >
            {{ item.name }}
          </a-button>
        </template>
        <!-- 序号 -->
        <template v-if="column.key === 'serial'">
          {{
            (localPagination.current - 1) * localPagination.pageSize + index + 1
          }}
        </template>
        <!-- 状态 -->
        <!-- <template v-else-if="column.key === 'status'">
          <span v-if="record.status === '已启用'">
            <span class="topoint"></span>
            <span class="green">{{ record.status }}</span>
          </span>
          <span v-else>
            <span class="red">{{ record.status }}</span>
          </span>
        </template> -->
         <!-- 列插槽 -->
         <template v-else-if="columnSlots.includes(column.dataIndex)">
          <template v-for="slot in columnSlots" :key="slot">
            <slot
              :name="`column-${slot}`"
              v-bind="{ text, record, index, column }"
            ></slot>
          </template>
        </template>
        <!-- 渲染customRender -->
        <template v-else-if="typeof column?.customRender === 'function'">
					<component :is="column.customRender" v-bind="{ text, record, index, column }"></component>
				</template>
      </template>
      <!-- 插槽透传 -->
      <template v-for="(value, name) in $slots" v-slot:[name]="slotProps">
				<slot :name="name" v-bind="slotProps"></slot>
			</template>
    </a-table>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, useSlots, unref } from 'vue'
  const props = defineProps({
    data: {
      type: [Function, Array],
      default: () => [],
    },
    //---------------------工具按钮--------------- -
    attachButtons: {
      type: Array,
      default: () => [],
    },
  })

  const slots = useSlots();
const columnSlots = ref([]);
const createColumnSlots = () => {
  columnSlots.value = Object.keys(slots)
    .filter((x) => x.indexOf("column") !== -1)
    .map((x) => x.split("-")[1]);
};



  // 表格操作列按钮显示/隐藏
  const btnShow = computed(
    () =>
      ({ item, record }) =>
        typeof item.show == 'function'
          ? item.show({ record })
          : item.show 
  )
  //表格操作列按钮禁止？
  const btnDisabled = computed(
    () =>
      ({ item, record}) =>
        typeof item.isDisabled == 'function'
          ? item.isDisabled({ record})
          : item.isDisabled 
  )
  //工具按钮的显示/隐藏
  const toolbtnShow = computed(
    () =>
      ({ btn }) =>
        typeof btn.show == 'function'  ? btn.show(): btn.show 
  )
  //工具按钮的置灰
  const toolbtnDisabled = computed(
    () =>
      ({ btn,selectedRowKeys}) =>
      typeof btn.isDisabled == 'function'  ? btn.isDisabled({ selectedRowKeys}): btn.isDisabled 
  )
  // 列表数据
  const dataSource = ref([])
  // -------------------分页--------------------------
  const localPagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total) => `共 ${total} 条记录`,
    showSizeChanger: true,
    showQuickJumper: true,
    onChange: (current, size) => {
      localPagination.current = current
      localPagination.pageSize = size
      loadTableData({ current, pageSize: size })
    },
    pageSizeOptions: ['10', '20', '30', '40', '50'],
  })
  // 是否分页
  const isPagination = ref(false)
  // loading状态
  const localLoading = ref(false)
  const selectedRowKeys = ref([])
  // 选中的行
  const onSelectChange = (rowKeys) => {
    console.log('rowKeys', rowKeys)
    selectedRowKeys.value = rowKeys
  }
  const localRowSelection = computed(() => {
    return {
      selectedRowKeys: unref(selectedRowKeys),
      onChange: onSelectChange,
    }
  })
  //重新加载渲染表格数据
  const loadTableData = (pagination) => {
    localLoading.value = true
    const params = isPagination.value
      ? {
          pageNo: pagination?.current
            ? pagination.current
            : localPagination.current,
          pageSize: pagination?.pageSize
            ? pagination.pageSize
            : localPagination.pageSize,
        }
      : {}
    //-------------------父组件接口返回数据传过来的---------------------
    if (!props.data) {
      dataSource.value = []
      return
    }
    if (Array.isArray(props.data)) {
      dataSource.value = props.data
      localLoading.value = false
    } else {
      props
        .data(params)
        .then((retObj) => {
          const { list, total, pageSize, pageNum } = retObj
          isPagination.value = retObj.hasOwnProperty('list')
          if (isPagination.value) {
            localPagination.total = total || 0
            localPagination.pageSize = pageSize
            localPagination.pageNum = pageNum
            dataSource.value = list?.length ? list : []
            if (list?.length === 0 && localPagination.current > 1) {
              localPagination.current--
              loadTableData()
            }
          } else {
            dataSource.value = retObj?.length ? retObj : []
          }
        })
        .finally(() => (localLoading.value = false))
    }
  }
  onMounted(() => {
    createColumnSlots();
    loadTableData()
  })

  defineExpose({ loadTableData })
</script>

<style scoped>
  .attach-buttons-wrap {
    margin-bottom: 10px;
  }

  .green {
    color: rgb(122, 185, 64);
  }

  .red {
    color: red;
  }
  .tableStyle .ant-btn {
    padding: 0px;
  }
</style>
